package com.sanjiahantang.youjiarole.module.decorate.views.impl;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.dialog.CommonDialog;
import com.sanjiahantang.uilibrary.popuwindow.SelectPhotoPopupwindow;
import com.sanjiahantang.uilibrary.utils.BitmapUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.module.common.adapters.ImageAddAdapter;
import com.sanjiahantang.youjiarole.module.common.beans.FileBean;
import com.sanjiahantang.youjiarole.module.decorate.presenters.DecorateManagePresenter;
import com.sanjiahantang.youjiarole.module.decorate.views.DecorateManageView;
import com.sanjiahantang.youjiarole.module.goods.beans.GoodsBean;
import com.sanjiahantang.youjiarole.utils.FileUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zy on 2017/11/24.
 */

public class SupervisionCheckActivity extends BaseMvpActivity<DecorateManageView,DecorateManagePresenter> implements DecorateManageView, View.OnClickListener {

    private GridView gridPic;
    private List<GoodsBean.Image> imageList;
    private LayoutInflater inflater;
    private BaseAdapter adapter;
    private int priId,piId;

    private SelectPhotoPopupwindow photoPopupwindow;
    private View rootView;
    private EditText txtEvaluate;
    private TextView txtCount;

    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    private static final int UPLOAD_PIC = 3;
    private static final int PHOTO_GRAPH = 0xF, SELECT_PICTURE = 3, INTENT_NICKNAME = 5, SAVE_PHOTO = 6;

    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    @Override
    public DecorateManagePresenter initPresenter() {
        return new DecorateManagePresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_supervision_check);
        rootView = findViewById(R.id.rootView);
        txtEvaluate = (EditText) rootView.findViewById(R.id.txtEvaluate);
        txtCount = (TextView) rootView.findViewById(R.id.txtCount);
        priId = getIntent().getIntExtra("priId",0);
        piId  = getIntent().getIntExtra("piId",0);
        if (priId == 0 || piId == 0){
            Utils.showToast($this,"步骤不存在");
            finish();
            return;
        }

        txtEvaluate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                txtCount.setText(String.format("%d/140",txtEvaluate.getText().toString().length()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        TextView title = (TextView) findViewById(R.id.title);
        title.setText("监理验收");
        findViewById(R.id.fl_Left).setOnClickListener(this);

        findViewById(R.id.btnSubmit).setOnClickListener(this);
        findViewById(R.id.btnRejected).setOnClickListener(this);
        inflater = LayoutInflater.from($this);
        gridPic = (GridView) findViewById(R.id.gridPic);
        imageList = new ArrayList<>();
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return imageList.size() + 1;
            }

            @Override
            public Object getItem(int i) {
                return i == getCount() - 1 ? null : imageList.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup viewGroup) {
                ViewHolder holder = null;
                if (position < imageList.size()){
                    convertView = inflater.inflate(R.layout.item_image, null);
                }else{
                    convertView = inflater.inflate(R.layout.item_add_image, null);
                }

                holder = new ViewHolder(convertView);
                holder.bind(getItem(position));

                return convertView;
            }
        };
        gridPic.setAdapter(adapter);
        photoPopupwindow = new SelectPhotoPopupwindow($this, this);
    }

    @Override
    public void initData() {
    }

    @Override
    public DecorateManagePresenter getPresenter() {
        return presenter;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnSubmit:
                Utils.showDialog($this, "", "确认验收?", "", "", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == CommonDialog.ID_POSITIVE){
                            presenter.updateEngnieeInfo($this,piId,priId,txtEvaluate.getText().toString(),1,new BaseView.OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {
                                    finish();
                                }
                            });
                        }
                        Utils.dismissDialog();
                    }
                });

                break;
            case R.id.btnRejected:
                Utils.showDialog($this, "", "确认拒绝?", "", "", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == CommonDialog.ID_POSITIVE){
                            presenter.updateEngnieeInfo($this,piId,priId,txtEvaluate.getText().toString(),0,new BaseView.OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {
                                    finish();
                                }
                            });
                        }
                        Utils.dismissDialog();
                    }
                });
                break;
            case R.id.fl_Left:
                finish();
                break;

            //拍照
            case R.id.btn_take_photo:
                photoPopupwindow.dismiss();
                if (ContextCompat.checkSelfPermission($this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    takePicture();
                }
                break;
            //相册
            case R.id.btn_pick_photo:
                photoPopupwindow.dismiss();
                presenter.cardSelect($this);
                break;
        }
    }

    private class ViewHolder{
        private View itemView;
        public ViewHolder(View itemView){
            this.itemView = itemView;
        }

        public void bind(Object obj) {
            if (obj instanceof GoodsBean.Image){
                final GoodsBean.Image img = (GoodsBean.Image) obj;
                ImageView iv = (ImageView) itemView.findViewById(R.id.image);
                Picasso.with($this).load(FileUtils.rePath(img.getUrl())).into(iv);
                iv.setTag(R.id.decode,img);
                View v = itemView.findViewById(R.id.ivClose);
                v.setVisibility(View.VISIBLE);
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        presenter.deleteImage($this,img.getId(), new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                removePic((int)content);
                            }
                        });
                    }
                });
            }else {
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        photoPopupwindow.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    }
                });
            }

        }
    }

    private void removePic(int id) {
        for (GoodsBean.Image pic : imageList){
            if (pic.getId() == id){
                imageList.remove(pic);
                adapter.notifyDataSetChanged();
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case INTENT_SELECT_PIC:
                    Uri uri0 = data.getData();
                    presenter.doUploadSupervisionCheckPic($this,uri0,priId, new BaseView.OnLoadListener() {
                        @Override
                        public void onLoad(Object content) {
                            FileBean.Data img = (FileBean.Data) content;
                            GoodsBean.Image bean = new GoodsBean.Image();
                            bean.setId(img.getPlanId());
                            bean.setUrl(img.getUrl());
                            imageList.add(bean);
                            adapter.notifyDataSetChanged();
                        }
                    });

                    break;

                case PHOTO_GRAPH:
                    if (data != null){
                        Bundle b = data.getExtras();
                        Bitmap bitmap = (Bitmap) b.get("data");
                        bitmap = BitmapUtils.resizeBitmap(bitmap, 480);
                        presenter.doUploadSupervisionCheckPic($this,bitmap,priId, new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                FileBean.Data img = (FileBean.Data) content;
                                GoodsBean.Image bean = new GoodsBean.Image();
                                bean.setId(img.getPlanId());
                                bean.setUrl(img.getUrl());
                                imageList.add(bean);
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }else{
                        Utils.showToast($this,"请从相册选择图片");
                    }
                    break;
            }
        }
    }

    private void takePicture(){
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try{
                startActivityForResult(takePhotoIntent, PHOTO_GRAPH);
            }catch (Exception e){
                e.printStackTrace();
                Utils.showToast($this,"请从相册上传图片");
            }
        } else
            Utils.showToast($this, "未插入SD卡");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePicture();
            } else {
                Utils.showToast(this, "权限被禁止，相关功能无法使用！");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
}
